<template>
  <div class="avatar-container" ref="avatarContainer">
    <img :src="currentAvatar" alt="User Avatar" class="avatar" @click="toggleDropdown" />
    <div v-if="showDropdown" class="avatar-hover">
      <!-- 未登录状态显示登录注册链接 -->
      <template v-if="!isLoggedIn">
        <router-link :to="{name: 'Login'}" class="menu-item">登录</router-link>
        <router-link :to="{name: 'Register'}" class="menu-item">注册</router-link>
      </template>
      <!-- 已登录状态显示用户菜单 -->
      <template v-else>
        <div class="user-info">
          <span class="nickname">{{ nickname }}</span>
          <div class="user-details">
            <span v-if="userStore.userInfo?.gender">{{ userStore.userInfo.gender === 1 ? '男' : '女' }}</span>
            <span v-if="userStore.userInfo?.age">{{ userStore.userInfo.age }}岁</span>
          </div>
        </div>
        <div class="menu-divider"></div>
        <router-link :to="{name: 'Profile'}" class="menu-item">个人资料</router-link>
        <a href="#" class="menu-item" @click.prevent="handleLogout">退出登录</a>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const avatarContainer = ref(null)

// 定义props
const props = defineProps({
  avatarUrl: {
    type: String,
    default: ''
  }
})

// 下拉菜单显示状态
const showDropdown = ref(false)

// 从store获取用户状态
const isLoggedIn = computed(() => userStore.isLoggedIn)
const nickname = computed(() => userStore.userInfo?.nickname || userStore.userInfo?.username || '未登录')

// 当前显示的头像
const currentAvatar = computed(() => {
  // 如果已登录且有头像
  if (isLoggedIn.value && userStore.userInfo?.avatar) {
    return userStore.userInfo.avatar
  }
  
  // 如果通过props传入了头像
  if (props.avatarUrl) {
    return props.avatarUrl
  }
  
  // 使用默认头像
  return '/images/default-avatar.png'
})

// 切换下拉菜单显示/隐藏
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event) => {
  if (avatarContainer.value && !avatarContainer.value.contains(event.target)) {
    showDropdown.value = false
  }
}

// 退出登录处理
const handleLogout = async () => {
  try {
    showDropdown.value = false // 先隐藏下拉菜单
    await userStore.logout()
    ElMessage.success('退出登录成功')
  } catch (error) {
    console.error('退出登录失败:', error)
    ElMessage.error('退出登录失败')
  }
}

// 初始化时检查用户状态
onMounted(() => {
  if (userStore.token && !userStore.userInfo) {
    userStore.fetchUserInfo()
  }
  // 添加点击外部关闭下拉菜单的事件监听
  document.addEventListener('click', handleClickOutside)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.avatar-container {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-hover {
  position: absolute;
  top: 100%;
  right: 0;
  min-width: 150px;
  background: white;
  padding: 0.5rem 0;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.user-info {
  padding: 0.5rem 1rem;
}

.nickname {
  display: block;
  font-weight: bold;
  color: #333;
  margin-bottom: 0.25rem;
}

.user-details {
  display: flex;
  gap: 0.5rem;
  font-size: 0.875rem;
  color: #666;
}

.menu-divider {
  height: 1px;
  background-color: #eee;
  margin: 0.5rem 0;
}

.menu-item {
  display: block;
  padding: 0.5rem 1rem;
  color: #333;
  text-decoration: none;
  transition: background-color 0.3s;
}

.menu-item:hover {
  background-color: #f5f5f5;
  color: #409eff;
}
</style>